package com.Utility;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import com.parser.Error_Report;
import com.parser.Parser_Soap;
import com.soap.call.Http_Soap_Call;

public class DownloadManager {
	public static final int DEFAULT_BUFFER_SIZE_IN_BYTES = 8 * 1024;
	public static final long MAXFILEAGE = 86400000L;// 669600000L; // 1 month in
													// milliseconds/4
	private ArrayList<QueueFile> lst;
	private DownloadTask download1;
	private DownloadTask download2;
	private DownloadTask download3;
	private DownloadTask download4;
	private Object obj;
	private Object obj1;
	private Context mContext;

	public DownloadManager(Context mContext) {
		this.mContext = mContext;
		lst = new ArrayList<DownloadManager.QueueFile>(100);
	}

	public void download(String fileName) {
		if (fileName == null || fileName.length() < 1)
			return;
		else {

			lst.add(new QueueFile(fileName));

			if (download1 == null) {
				download1 = new DownloadTask() {
					@Override
					protected void onPostExecute(Void result) {
						download1 = null;
						if (download2 == null && download3 == null
								&& download4 == null) {
							onFinish();
						}
					}
				};
				download1.execute();
			} else if (download2 == null) {
				download2 = new DownloadTask() {
					@Override
					protected void onPostExecute(Void result) {
						download2 = null;
						if (download1 == null && download3 == null
								&& download4 == null) {
							onFinish();
						}
					}
				};
				download2.execute();
			} else if (download3 == null) {
				download3 = new DownloadTask() {
					@Override
					protected void onPostExecute(Void result) {
						download3 = null;
						if (download2 == null && download1 == null
								&& download4 == null) {
							onFinish();
						}
					}
				};
				download3.execute();
			} else if (download4 == null) {
				download4 = new DownloadTask() {
					@Override
					protected void onPostExecute(Void result) {
						download4 = null;
						if (download2 == null && download3 == null
								&& download1 == null) {
							onFinish();
						}
					}
				};
				download4.execute();
			}
		}
	};

	public class DownloadTask extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... params) {
			synchronized (lst) {
				while (lst.size() > 0) {
					QueueFile file = lst.remove(0);
					if (file != null) {
						String name = file.getName();
						try {
							Log.e("=--------begin--------", name);
							downloadFile(name);
							Log.e("=--------finish--------", name);
						} catch (Exception e) {
							e.printStackTrace();
							deleteFiles(Configs.FILE_STORE + name);
						}
					}
				}
			}
			return null;
		}
	}

	public class QueueFile {
		private String name;

		public QueueFile(String name) {
			super();
			this.name = name;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}

	public void onFinish() {

	}

	public void downloadFile(String fileName) throws Exception {
		if (isExist(Configs.FILE_STORE + fileName))
			return;
		long fileSize;
		long count;

		StringBuffer content = new StringBuffer("");
		Parser_Soap parse = new Parser_Soap();
		Error_Report repor = new Error_Report();
		try {
			Http_Soap_Call call = Http_Soap_Call
					.create_connection("", mContext);
			if (call != null) {
				InputStream in = call.getDownloadFilesSize((Utility
						.getStringPreference(mContext, "LoginToken", "1")),
						fileName, repor);
				if (in != null) {
					fileSize = Long.parseLong(parse.parseFileSize(in, repor));

					count = fileSize / 262144;

					if (fileSize % 262144 != 0)
						count = count + 1;
					int i = 0;
					Log.e("Count", count + "");
					do {
						Log.e("Count pos", i + "");
						Http_Soap_Call call1 = Http_Soap_Call
								.create_connection("", mContext);
						if (call1 != null) {
							InputStream in1 = call1.downloadFilesFromVault(
									Utility.getStringPreference(mContext,
											"LoginToken", "1"), fileName,
									i * 262144, repor);
							if (in1 != null) {
								content.append(parse.GetFileUploadResponse(in1,
										repor));
							}
						} else {
							repor.setMessage(Utility.NETWORK_ISSUE);
						}
						i++;
					} while (i < count);

					byte res[] = android.util.Base64.decode(content.toString(),
							android.util.Base64.NO_PADDING);

					File f = new File(Configs.FILE_STORE + fileName);
					f.createNewFile();
					FileOutputStream fout = new FileOutputStream(f);
					fout.write(res);
					fout.flush();
					fout.close();

					Log.e("DownloadFileTask", "File succssfully saved");
					Log.e("DownloadFileTask file size", f.length() + "");

				}
			} else {
				repor.setMessage(Utility.NETWORK_ISSUE);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return;

	}

	public boolean isDownloading() {
		if (lst != null && lst.size() > 0) {
			for (QueueFile item : lst) {
				Log.e("FILE", item.getName());
			}
			return true;
		} else
			return false;
	}

	public boolean isHasFile(String name) {
		if (lst != null && lst.size() > 0) {
			for (QueueFile item : lst) {
				if (item.getName().equals(name)) {
					return true;
				}
			}
		}
		return false;
	}

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}

	public Object getObj1() {
		return obj1;
	}

	public void setObj1(Object obj1) {
		this.obj1 = obj1;
	}

	public boolean deleteFiles(String path) {
		File file = new File(path);
		if (file.exists()) {
			String deleteCmd = "rm -r " + path;
			Runtime runtime = Runtime.getRuntime();
			try {
				runtime.exec(deleteCmd);
			} catch (IOException e) {
				return false;
			}
		}
		return true;
	}

	public static boolean isExist(String path) {
		File file = new File(path);
		if (file.exists()) {
			return true;
		}
		return false;
	}

	public void prepareFolder(String pfolder) {
		File folder = new File(pfolder);
		folder.mkdirs();
		new ClearFiles(pfolder, MAXFILEAGE).start();
	}

	public class ClearFiles extends Thread {
		private String path;
		private long day;

		public ClearFiles(String path, Long dayinmiliseconds) {
			this.path = path;
			this.day = dayinmiliseconds;
		}

		@Override
		public void run() {
			File dir = new File(path);
			File[] files = dir.listFiles();
			// Loop through all files
			for (File f : files) {
				// Get the last modified date. Miliseconds since 1970
				Long lastmodified = f.lastModified();
				// Do stuff here to deal with the file..
				// For instance delete files older than 1 month
				if (lastmodified + day < System.currentTimeMillis()) {
					f.delete();
				}
			}
		}
	}
}
